/**
 * 游戏管理路由
 * 处理游戏上传、查询、编辑和删除的API端点
 */

const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const Game = require('../models/game');
const Comment = require('../models/comment');
const { protect, admin, checkOwnership } = require('../middleware/auth');
const { uploadGameFile, uploadThumbnail, handleUploadError } = require('../middleware/upload');
const { ErrorResponse } = require('../middleware/error');

/**
 * @desc    获取游戏列表
 * @route   GET /api/v1/games
 * @access  公开
 */
router.get('/', async (req, res, next) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 12;
        const category = req.query.category;
        const startIndex = (page - 1) * limit;
        
        // 构建查询条件
        const query = { status: 'approved' };
        if (category) query.category = category;
        
        // 查询游戏总数
        const total = await Game.countDocuments(query);
        
        // 查询游戏列表
        const games = await Game.find(query)
            .sort({ createdAt: -1 })
            .skip(startIndex)
            .limit(limit)
            .populate('author', 'username avatar');
        
        res.status(200).json({
            success: true,
            count: games.length,
            total,
            page,
            pages: Math.ceil(total / limit),
            games
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    获取热门游戏
 * @route   GET /api/v1/games/hot
 * @access  公开
 */
router.get('/hot', async (req, res, next) => {
    try {
        const limit = parseInt(req.query.limit) || 10;
        
        // 使用Game模型的静态方法获取热门游戏
        const games = await Game.getHotGames(limit);
        
        res.status(200).json({
            success: true,
            count: games.length,
            games
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    获取最新游戏
 * @route   GET /api/v1/games/new
 * @access  公开
 */
router.get('/new', async (req, res, next) => {
    try {
        const limit = parseInt(req.query.limit) || 10;
        
        // 使用Game模型的静态方法获取最新游戏
        const games = await Game.getNewGames(limit);
        
        res.status(200).json({
            success: true,
            count: games.length,
            games
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    获取推荐游戏
 * @route   GET /api/v1/games/featured
 * @access  公开
 */
router.get('/featured', async (req, res, next) => {
    try {
        const limit = parseInt(req.query.limit) || 10;
        
        // 使用Game模型的静态方法获取推荐游戏
        const games = await Game.getFeaturedGames(limit);
        
        res.status(200).json({
            success: true,
            count: games.length,
            games
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    按分类获取游戏
 * @route   GET /api/v1/games/category/:category
 * @access  公开
 */
router.get('/category/:category', async (req, res, next) => {
    try {
        const { category } = req.params;
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 12;
        
        // 验证分类是否有效
        const validCategories = ['casual', 'action', 'puzzle', 'strategy', 'adventure'];
        if (!validCategories.includes(category)) {
            return next(new ErrorResponse('无效的游戏分类', 400));
        }
        
        // 使用Game模型的静态方法按分类获取游戏
        const games = await Game.getGamesByCategory(category, limit, page);
        
        // 获取分类游戏总数
        const total = await Game.countDocuments({ status: 'approved', category });
        
        res.status(200).json({
            success: true,
            count: games.length,
            total,
            page,
            pages: Math.ceil(total / limit),
            games
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    搜索游戏
 * @route   GET /api/v1/games/search
 * @access  公开
 */
router.get('/search', async (req, res, next) => {
    try {
        const { q } = req.query;
        if (!q) {
            return next(new ErrorResponse('请提供搜索关键词', 400));
        }
        
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 12;
        
        // 使用Game模型的静态方法搜索游戏
        const games = await Game.searchGames(q, limit, page);
        
        // 获取搜索结果总数
        const total = await Game.countDocuments({
            status: 'approved',
            $text: { $search: q }
        });
        
        res.status(200).json({
            success: true,
            count: games.length,
            total,
            page,
            pages: Math.ceil(total / limit),
            games
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    获取游戏详情
 * @route   GET /api/v1/games/:id
 * @access  公开
 */
router.get('/:id', async (req, res, next) => {
    try {
        // 获取游戏ID
        const { id } = req.params;
        
        // 查找游戏并填充作者信息
        const game = await Game.findById(id).populate('author', 'username avatar bio');
        
        // 如果游戏不存在
        if (!game) {
            return next(new ErrorResponse('游戏不存在', 404));
        }
        
        // 如果游戏未审核通过，只有作者和管理员可以查看
        if (game.status !== 'approved') {
            // 检查用户是否已登录
            if (!req.user) {
                return next(new ErrorResponse('游戏不存在或未审核通过', 404));
            }
            
            // 检查用户是否为作者或管理员
            const isAuthor = req.user._id.toString() === game.author._id.toString();
            const isAdmin = req.user.role === 'admin';
            
            if (!isAuthor && !isAdmin) {
                return next(new ErrorResponse('游戏不存在或未审核通过', 404));
            }
        }
        
        // 增加游戏浏览量
        game.plays += 1;
        await game.save();
        
        res.status(200).json({
            success: true,
            game
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    上传新游戏
 * @route   POST /api/v1/games
 * @access  私有
 */
router.post('/', protect, uploadGameFile, uploadThumbnail, handleUploadError, async (req, res, next) => {
    try {
        // 检查必填字段
        const { title, category, description } = req.body;
        
        if (!title || !category || !description) {
            return next(new ErrorResponse('请提供游戏标题、分类和描述', 400));
        }
        
        // 检查文件是否上传
        if (!req.files || !req.files.gameFile) {
            return next(new ErrorResponse('请上传游戏文件', 400));
        }
        
        if (!req.files || !req.files.thumbnail) {
            return next(new ErrorResponse('请上传游戏缩略图', 400));
        }
        
        // 获取上传的文件信息
        const gameFile = req.files.gameFile[0];
        const thumbnail = req.files.thumbnail[0];
        
        // 创建游戏记录
        const game = await Game.create({
            title,
            category,
            description,
            filePath: gameFile.path,
            fileType: path.extname(gameFile.originalname).toLowerCase(),
            fileSize: gameFile.size,
            thumbnail: thumbnail.path,
            author: req.user._id,
            tags: req.body.tags ? req.body.tags.split(',').map(tag => tag.trim()) : []
        });
        
        res.status(201).json({
            success: true,
            message: '游戏上传成功，等待审核',
            game_id: game._id
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    更新游戏信息
 * @route   PUT /api/v1/games/:id
 * @access  私有（只有作者和管理员可以编辑）
 */
router.put('/:id', protect, checkOwnership(Game), async (req, res, next) => {
    try {
        const { title, category, description, tags } = req.body;
        
        // 创建更新对象
        const updateData = {};
        if (title) updateData.title = title;
        if (category) updateData.category = category;
        if (description) updateData.description = description;
        if (tags) updateData.tags = tags.split(',').map(tag => tag.trim());
        
        // 更新游戏信息
        const game = await Game.findByIdAndUpdate(
            req.params.id,
            updateData,
            { new: true, runValidators: true }
        );
        
        res.status(200).json({
            success: true,
            message: '游戏信息更新成功',
            game
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    删除游戏
 * @route   DELETE /api/v1/games/:id
 * @access  私有（只有作者和管理员可以删除）
 */
router.delete('/:id', protect, checkOwnership(Game), async (req, res, next) => {
    try {
        const game = req.resource; // 从checkOwnership中间件获取游戏对象
        
        // 删除游戏文件
        if (fs.existsSync(game.filePath)) {
            fs.unlinkSync(game.filePath);
        }
        
        // 删除缩略图文件
        if (fs.existsSync(game.thumbnail)) {
            fs.unlinkSync(game.thumbnail);
        }
        
        // 删除游戏相关的评论
        await Comment.deleteMany({ game: game._id });
        
        // 删除游戏记录
        await Game.findByIdAndDelete(req.params.id);
        
        res.status(200).json({
            success: true,
            message: '游戏已删除'
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    审核游戏
 * @route   PUT /api/v1/games/:id/review
 * @access  私有（只有管理员可以审核）
 */
router.put('/:id/review', protect, admin, async (req, res, next) => {
    try {
        const { status } = req.body;
        
        // 验证状态值
        if (!['approved', 'rejected'].includes(status)) {
            return next(new ErrorResponse('无效的审核状态', 400));
        }
        
        // 更新游戏状态
        const game = await Game.findByIdAndUpdate(
            req.params.id,
            { status },
            { new: true }
        );
        
        // 如果游戏不存在
        if (!game) {
            return next(new ErrorResponse('游戏不存在', 404));
        }
        
        res.status(200).json({
            success: true,
            message: status === 'approved' ? '游戏已通过审核' : '游戏已被拒绝',
            game
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    获取游戏评论
 * @route   GET /api/v1/games/:id/comments
 * @access  公开
 */
router.get('/:id/comments', async (req, res, next) => {
    try {
        const { id } = req.params;
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const startIndex = (page - 1) * limit;
        
        // 检查游戏是否存在
        const gameExists = await Game.exists({ _id: id });
        if (!gameExists) {
            return next(new ErrorResponse('游戏不存在', 404));
        }
        
        // 查询评论总数
        const total = await Comment.countDocuments({ game: id });
        
        // 查询评论列表
        const comments = await Comment.find({ game: id })
            .sort({ createdAt: -1 })
            .skip(startIndex)
            .limit(limit)
            .populate('user', 'username avatar');
        
        res.status(200).json({
            success: true,
            count: comments.length,
            total,
            page,
            pages: Math.ceil(total / limit),
            comments
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    添加游戏评论
 * @route   POST /api/v1/games/:id/comments
 * @access  私有
 */
router.post('/:id/comments', protect, async (req, res, next) => {
    try {
        const { id } = req.params;
        const { content, rating } = req.body;
        
        // 检查必填字段
        if (!content || !rating) {
            return next(new ErrorResponse('请提供评论内容和评分', 400));
        }
        
        // 检查游戏是否存在
        const game = await Game.findById(id);
        if (!game) {
            return next(new ErrorResponse('游戏不存在', 404));
        }
        
        // 检查游戏是否已审核通过
        if (game.status !== 'approved') {
            return next(new ErrorResponse('只能评论已审核通过的游戏', 400));
        }
        
        // 检查用户是否已评论过该游戏
        const existingComment = await Comment.findOne({
            game: id,
            user: req.user._id
        });
        
        if (existingComment) {
            return next(new ErrorResponse('您已经评论过该游戏', 400));
        }
        
        // 创建评论
        const comment = await Comment.create({
            game: id,
            user: req.user._id,
            content,
            rating: parseInt(rating)
        });
        
        // 填充用户信息
        await comment.populate('user', 'username avatar');
        
        res.status(201).json({
            success: true,
            message: '评论成功',
            comment
        });
    } catch (error) {
        next(error);
    }
});

module.exports = router; 